package com.mrjy.integral.bo;

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.mrjy.common.dto.UserAddressDTO;
import com.mrjy.common.entity.IntegralExchange;
import com.mrjy.common.entity.IntegralExchangedLog;
import com.mrjy.common.entity.UserAddress;
import com.mrjy.common.entity.UserInfo;
import com.mrjy.common.util.DateUtil;
import com.mrjy.common.util.ExcelUtil;
import com.mrjy.common.util.GlobalConstant;
import com.mrjy.integral.dao.IIntegralExchangeDao;
import com.mrjy.integral.dao.IIntegralExchangedLogDao;
import com.mrjy.integral.dao.IIntegralInfoDao;
import com.mrjy.integral.dto.IntegralExchangeDTO;
import com.mrjy.integral.dto.IntegralExchangedLogDTO;
import com.mrjy.integral.dto.IntegralExchangedOrderDTO;
import com.mrjy.integral.util.IntegralEnum;
import com.mrjy.integral.util.IntegralUtil;
import com.mrjy.maintain.dao.IUserAddressDao;
import com.mrjy.maintain.dao.IUserInfoDao;

@Service
public class IntegralExchangedLogBo implements IIntegralExchangedLogBo {
	
	@Resource
	private IIntegralExchangedLogDao integralExchangedLogDao;
	@Resource
	private IUserAddressDao userAddressDao;
	@Resource
	private IIntegralInfoDao integralInfoDao;
	@Resource
	private IIntegralExchangeDao integralExchangeDao;
	@Resource
	private IUserInfoDao userInfoDao;

	@Override
	public Object queryByUserId(IntegralExchangedLogDTO dto,HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
//		if(null == loginUser || exchangedLog.getUserId().intValue() == 0){
//			//游客
//			map.put("err_code", -1);
//			map.put("err_msg", "当前用户为游客");
//			map.put("rows", null);
//			map.put("total", 0);
//			return map;
//		}
		List<IntegralExchangeDTO> list = null;
		try {
			int count = integralExchangedLogDao.countByUserId(dto);
			if (count>0) {
				list = integralExchangedLogDao.queryByUserId(dto);
			}
			map.put("err_code", 200);
			map.put("err_msg", "查询成功");
			map.put("rows", list);
			map.put("total", count);
		} catch (Exception e) {
			e.printStackTrace();
			map.put("err_code", 500);
			map.put("err_msg", "查询失败");
		}
		return map;
	}

	@Override
	public Object queryIEDetail(IntegralExchangedLog exchangedLog,
			HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
//		if(null == loginUser || exchangedLog.getUserId().intValue() == 0){
//			//游客
//			map.put("err_code", -1);
//			map.put("err_msg", "当前用户为游客");
//			map.put("rows", null);
//			map.put("total", 0);
//			return map;
//		}
		try {
			IntegralExchangedLogDTO dto = integralExchangedLogDao.queryIEDetailById(exchangedLog);
			//如果该兑换物是实物,又没有填写收货地址,则需要用户填写地址
			if (dto.getTypeId().intValue()==0 && StringUtils.isBlank(dto.getAddress())) {
				map.put("err_code", 1);
				map.put("err_msg", "查询成功,用户未填写收货地址");
			}else {
				map.put("err_code", 200);
				map.put("err_msg", "查询成功");
			}
			map.put("rows", dto);
		} catch (Exception e) {
			e.printStackTrace();
			map.put("err_code", 500);
			map.put("err_msg", "查询失败");
		}
		return map;
	}

	@Override
	public Object txInsert(IntegralExchangedLogDTO dto,
			HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		synchronized (this) {
			int integralBalance = userInfoDao.queryIntegralBalanceByUserId(dto.getUserId());
			if(null == loginUser || dto.getUserId().intValue() == 0){
				//游客
				map.put("err_code", -1);
				map.put("err_msg", "用户未登录,无法兑换");
				return map;
			}
			//积分不足, 无法兑换
			if (dto.getScore().intValue() > integralBalance) {
				map.put("err_code", 401);
				map.put("err_msg", "积分不足,无法兑换");
				return map;
			}
			//余量不足,无法兑换
			IntegralExchange exchange = integralExchangeDao.queryById(dto.getIntegralExchangeId());
			if (exchange.getCountBalance()!=null && exchange.getCountBalance().intValue()<=0) {
				map.put("err_code", 402);
				map.put("err_msg", "余量不足,无法兑换");
				return map;
			}
			//补助券一人只能领取一张
			if (exchange.getTypeId().intValue()==2) {
				IntegralExchangedLog log = new IntegralExchangedLog();
				log.setUserId(dto.getUserId());
				log.setIntegralExchangeId(dto.getIntegralExchangeId());
				IntegralExchangedLog existVoucher = integralExchangedLogDao.queryByUserIdAndIEId(log);
				if (existVoucher!=null) {
					map.put("err_code", 403);
					map.put("err_msg", "您已经领取过补助券");
					return map;
				}
			}
			try {
				IntegralExchangedLog log = new IntegralExchangedLog();
				log.setUserId(dto.getUserId());
				log.setIntegralExchangeId(dto.getIntegralExchangeId());
				log.setExchangedTime(new Timestamp(System.currentTimeMillis()));//兑换时间
				if (dto.getValidDateNum()==null) {//有效天数为空,则是永久有效
					log.setExpireTime(null);
				}else if (dto.getTypeId().intValue() == 2) {//补助券领取后1年内有效
					log.setExpireTime(new Timestamp(DateUtil.dateTimeAddMonths(System.currentTimeMillis(), 12)));
				}else {
					log.setExpireTime(new Timestamp(DateUtil.dateTimeAddDays(System.currentTimeMillis(), dto.getValidDateNum())));
				}
				log.setIsPost(0);//未邮寄
				log.setCreateTime(new Timestamp(System.currentTimeMillis()));
				log.setDisableFlag(0);
				if (dto.getTypeId()==1||dto.getTypeId()==2) {
					log.setIsUse(0);//默认代金券/补助券未使用
				}
				int row = integralExchangedLogDao.insert(log);
				if (row>0) {
					//如果兑换的是实物, 则查询是否有地址
					if (dto.getTypeId().intValue()==0) {
						UserAddress address = new UserAddress();
						address.setUserId(dto.getUserId());
						List<UserAddressDTO> list = userAddressDao.queryByUserId(address);
						if (list != null && list.size()>0) {//有地址
							map.put("hasAddress", "true");
						}else {
							map.put("hasAddress", "false");
						}
					}
					//增加一条积分扣除记录
					integralInfoDao.insert(IntegralUtil.setIntegral(dto.getUserId(), -dto.getScore(),
							"积分兑换", IntegralEnum.INTEGRAL_EXCHANGE.getTypeId(), dto.getIntegralExchangeId()));
					
					//余量减1
					if (exchange.getCountBalance() != null) {
						exchange.setCountBalance(exchange.getCountBalance()-1);
						integralExchangeDao.updateById(exchange);
					}
					
					map.put("err_code", 200);
					map.put("err_msg", "兑换成功");
					map.put("id", log.getId());
				}else {
					map.put("err_code", 500);
					map.put("err_msg", "兑换失败");
				}
			} catch (Exception e) {
				e.printStackTrace();
				map.put("err_code", 500);
				map.put("err_msg", "兑换失败");
			}
			return map;
		}
	}
	
	@Override
	public Object txUpdate(IntegralExchangedLogDTO dto, HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
//		if(null == loginUser){
//			map.put("err_code", -1);
//			map.put("err_msg", "用户未登录");
//			return map;
//		}
		
		try {
			IntegralExchangedLog log = new IntegralExchangedLog();
			log.setId(dto.getId());
			log.setUserAddressId(dto.getUserAddressId());
			int row = integralExchangedLogDao.updateById(log);
			if(row > 0){
				map.put("err_code", 200);
				map.put("err_msg", "提交成功");
			}else {
				map.put("err_code", 500);
				map.put("err_msg", "提交失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
			map.put("err_code", 500);
			map.put("err_msg", "提交失败");
		}
		return map;
	}

	@Override
	public Object queryPageForBack(IntegralExchangedLogDTO dto,
			HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
//		if(null == loginUser){
//			map.put("err_code", -1);
//			map.put("err_msg", "用户未登录");
//			return map;
//		}
		try {
			int count = integralExchangedLogDao.queryCountForBack(dto);
			if (count > 0) {
				List<IntegralExchangedLogDTO> list = integralExchangedLogDao.queryPageForBack(dto);
				map.put("err_code", 200);
				map.put("err_msg", "查询成功");
				map.put("total", count);
				map.put("rows", list);
			}else {
				map.put("err_code", 200);
				map.put("err_msg", "查询成功,无数据");
				map.put("total", count);
				map.put("rows", null);
			}
		} catch (Exception e) {
			e.printStackTrace();
			map.put("err_code", 500);
			map.put("err_msg", "查询失败");
		}
		return map;
	}
	
	@Override
	public Object queryPageUsedForBack(IntegralExchangedOrderDTO dto,
			HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
//		if(null == loginUser){
//			map.put("err_code", -1);
//			map.put("err_msg", "用户未登录");
//			return map;
//		}
		try {
			int count = integralExchangedLogDao.queryCountUsedForBack(dto);
			if (count > 0) {
				List<IntegralExchangedOrderDTO> list = integralExchangedLogDao.queryPageUsedForBack(dto);
				map.put("err_code", 200);
				map.put("err_msg", "查询成功");
				map.put("total", count);
				map.put("rows", list);
			}else {
				map.put("err_code", 200);
				map.put("err_msg", "查询成功,无数据");
				map.put("total", count);
				map.put("rows", null);
			}
		} catch (Exception e) {
			e.printStackTrace();
			map.put("err_code", 500);
			map.put("err_msg", "查询失败");
		}
		return map;
	}

	@Override
	public Object updateDisableFlag(IntegralExchangedLog exchangedLog,
			HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
//		if(null == loginUser){
//			map.put("err_code", -1);
//			map.put("err_msg", "用户未登录");
//			return map;
//		}
		try {
			int row = integralExchangedLogDao.updateDisableFlag(exchangedLog);
			map.put("err_code", 200);
			map.put("err_msg", "成功操作"+row+"条记录");
			return map;
		} catch (Exception e) {
			e.printStackTrace();
			map.put("err_code", 500);
			map.put("err_msg", "操作失败");
		}
		return map;
	}

	@Override
	public Object doPost(IntegralExchangedLog exchangedLog, HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
//		if(null == loginUser){
//			map.put("err_code", -1);
//			map.put("err_msg", "用户未登录");
//			return map;
//		}
		if (StringUtils.isBlank(exchangedLog.getExpressName())) {
			map.put("err_code", 401);
			map.put("err_msg", "快递运营商不能为空");
			return map;
		}
		if (StringUtils.isBlank(exchangedLog.getExpressOrderNum())) {
			map.put("err_code", 401);
			map.put("err_msg", "快递单号不能为空");
			return map;
		}
		try {
			exchangedLog.setExpressName(exchangedLog.getExpressName());
			exchangedLog.setExpressOrderNum(exchangedLog.getExpressOrderNum());
			exchangedLog.setIsPost(1);
			exchangedLog.setExpressPostTime(new Timestamp(System.currentTimeMillis()));
			int row = integralExchangedLogDao.updateById(exchangedLog);
			if (row > 0) {
				map.put("err_code", 200);
				map.put("err_msg", "操作成功");
			}else {
				map.put("err_code", 500);
				map.put("err_msg", "操作失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
			map.put("err_code", 500);
			map.put("err_msg", "操作失败");
		}
		return map;
	}

	@Override
	public Object export(IntegralExchangedLogDTO dto, HttpSession session,
			HttpServletResponse response) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
//		if(null == loginUser){
//			map.put("err_code", -1);
//			map.put("err_msg", "用户未登录");
//			return map;
//		}
		try {
			List<IntegralExchangedLogDTO> dataset = integralExchangedLogDao.queryPageForBack(dto);
			if (dataset == null || dataset.size()==0) {
				map.put("err_code", 404);
				map.put("err_msg", "无可导出数据");
				return map;
			}
			ExcelUtil.writeExcel(response, "兑换日志"+DateUtil.dateToString(new Date(), DateUtil.FULL_DATE_STR)+".xls", dataset, IntegralExchangedLogDTO.class);
			map.put("err_code", 200);
			map.put("err_msg", "导出成功");
		} catch (Exception e) {
			e.printStackTrace();
			map.put("err_code", 500);
			map.put("err_msg", "导出失败");
		}
		return map;
	}

	@Override
	public Object exportUsed(IntegralExchangedOrderDTO dto, HttpSession session,
			HttpServletResponse response) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
//		if(null == loginUser){
//			map.put("err_code", -1);
//			map.put("err_msg", "用户未登录");
//			return map;
//		}
		try {
			List<IntegralExchangedOrderDTO> dataset = integralExchangedLogDao.queryPageUsedForBack(dto);
			if (dataset == null || dataset.size()==0) {
				map.put("err_code", 404);
				map.put("err_msg", "无可导出数据");
				return map;
			}
			for (IntegralExchangedOrderDTO orderDTO : dataset) {
				switch (orderDTO.getTypeId()) {
				//(2:会员 4:课程包 6：付费偷听 8:付费提问 9:购买微课
				case 2:
					orderDTO.setTypeName("开通会员");
					break;
				case 4:
					orderDTO.setTypeName("购买课程包");
					break;
				case 6:
					orderDTO.setTypeName("付费偷听");
					break;
				case 8:
					orderDTO.setTypeName("付费提问");
					break;
				case 9:
					orderDTO.setTypeName("购买微课");
					break;
				default:
					break;
				}
			}
			ExcelUtil.writeExcel(response, "代金券消费日志"+DateUtil.dateToString(new Date(), DateUtil.FULL_DATE_STR)+".xls", dataset, IntegralExchangedOrderDTO.class);
			map.put("err_code", 200);
			map.put("err_msg", "导出成功");
		} catch (Exception e) {
			e.printStackTrace();
			map.put("err_code", 500);
			map.put("err_msg", "导出失败");
		}
		return map;
	}

}
